# -*- coding: UTF-8 -*-
import os
import time
import logging
import traceback
import logging.handlers
from functools import wraps
from tools.handle_path import log_path


class MyLog(object):
    """
    日志打印 INFO 普通信息
            WARRING 警告信息
            DEBUG 调试信息
            ERROR 错误信息
            CRITICAL 严重警告
    """

    def __init__(self, CL=False, WF=False):
        """
        CL(close logger) 关闭、开启日志
        WF(write file) 写入、不写入*.log
        """
        self.CL = CL
        self.WF = WF

    def mylog(self, msg, msg_level, log_name='auto_case', level='DEBUG'):
        """
        msg 打印信息
        msg_level ：消息等级
        """
        if self.CL:
            if not os.path.exists(log_path):
                os.makedirs(log_path)
            file_path = os.path.join(log_path, time.strftime('%Y%m%d', time.localtime()) + '.log')
            logger = logging.getLogger(log_name)
            logger.setLevel(level)
            fh = None
            if self.WF:
                fh = logging.FileHandler(file_path, encoding='utf-8')
                fh.setLevel(level)

            sh = logging.StreamHandler()  # 实时打印
            sh.setLevel(level)

            # formatter = logging.Formatter('[%(levelname)s]%(asctime)s[日志信息]:%(message)s')
            formatter = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
            if self.WF:
                fh.setFormatter(formatter)
                logger.addHandler(fh)

            sh.setFormatter(formatter)
            logger.addHandler(sh)

            if msg_level == 'DEBUG':
                logger.debug(msg)
            elif msg_level == 'INFO':
                logger.info(msg)
            elif msg_level == 'WARNING':
                logger.warning(msg)
            elif msg_level == 'ERROR':
                logger.error(msg)
            elif msg_level == 'CRITICAL':
                logger.critical(msg)

            # 使用完以后需要移除
            logger.removeHandler(sh)
            if self.WF:
                logger.removeHandler(fh)
                # 关闭文件流
                fh.close()

    def debug(self, msg):
        self.mylog(msg, 'DEBUG')

    def info(self, msg):
        self.mylog(msg, 'INFO')

    def warning(self, msg):
        self.mylog(msg, 'WARNING')

    def error(self, msg):
        self.mylog(msg, 'ERROR')

    def critical(self, msg):
        self.mylog(msg, 'CRITICAL')


def _getLogger(fileLog=False, name=__name__):
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    file_path = os.path.join(log_path, f'{time.strftime("%Y-%m-%d", time.localtime())}.log')
    # 日志收集器对象
    logObject = logging.getLogger(name)
    # 设置日志级别
    logObject.setLevel(logging.INFO)
    # 日志格式内容
    formatter = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
    if fileLog:  # log文件模式
        # 设置日志渠道-文件输出
        handle = logging.FileHandler(file_path, encoding="utf-8")
    else:
        # 设置日志渠道-控制台输出
        handle = logging.StreamHandler()
    # 日志内容与渠道绑定
    handle.setFormatter(formatter)
    # 日志对象与渠道绑定
    logObject.addHandler(handle)
    return logObject


def decorator_log(func):
    @wraps(func)
    def log(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            _getLogger().error(f"\n{func.__qualname__} is error,here are details:\n{traceback.format_exc()}")

    return log


LOG = _getLogger()

if __name__ == '__main__':
    _getLogger().info("demo")
